package edu.cuc.spring.config.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.ServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Component
public class TimeServer {
    @Resource(name = "bootStrap")
    private ServerBootstrap serverBootstrap;
    @Resource(name = "workGroup")
    private NioEventLoopGroup workGroup;
    @Resource(name = "bossGroup")
    private NioEventLoopGroup bossGroup;
    @Resource(name = "timeServerIni")
    private TimeServerIni timeServerIni;
    @PostConstruct
    public void bind() {
        try {

            serverBootstrap.group(workGroup, bossGroup).channel(NioServerSocketChannel.class).childOption(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(timeServerIni);
            ChannelFuture f = serverBootstrap.bind(9999);
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @PreDestroy
    public void close() {
        workGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
